
#import "RoundsViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Player.h"
#import "TimerGame.h"
#import "LabelGameComponent.h"
#import "ImageGameComponent.h"
#import "Reactor.h"
#import "ColorNameGame.h"
#import "MathGame.h"
#import "WhiteScreenGame.h"
#import "CapitalsGame.h"
#import "PopulationGame.h"
#import "TicTacToeGame.h"
#import "DirectionsGame.h"
#import "SadFaceGame.h"
#import "ThreeOfAKindGame.h"
#import "FiguresGame.h"
#import "MouseCheeseGame.h"
#import "MorePlusThanMinus.h"
#import "ResultsViewController.h"
#import "SoundDelegate.h"
#import "GamesToPlayTableViewController.h"

@interface RoundsViewController ()
@property (weak, nonatomic) IBOutlet UIButton *playerTwoButton;
@property (weak, nonatomic) IBOutlet UIButton *playerOneButton;
@property (weak, nonatomic) IBOutlet UILabel *playerOneLabel;
@property (weak, nonatomic) IBOutlet UILabel *playerTwoLabel;
@property (weak, nonatomic) IBOutlet UIView *gameView;
@property Reactor* reactor;
@property Game* currentGame;
@property NSInteger test;
@property NSInteger currentRound;
@property BOOL isButtonClick;

@property (nonatomic)  NSMutableArray* textsForRightAnswer;
@property (nonatomic)  NSMutableArray* textsForWrongAnswer;
@property (weak, nonatomic) IBOutlet UILabel *playerOneScoreLabel;
@property (weak, nonatomic) IBOutlet UILabel *playerTwoScoreLabel;
@property Settings* settings;
@property SoundDelegate* soundPlayer;

@end

@implementation RoundsViewController

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimerGame:)name:@"TimerGame"object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SomeGames:)name:@"SomeGames" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whiteScreenFunc: ) name:@"white" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TTTGame :  ) name:@"TTTupdateView" object:nil];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
   
    //init settings
    self.settings=[Settings sharedSettings];
    if (self.settings.showScore == YES ) {
        self.playerTwoScoreLabel.hidden=NO;
        self.playerOneScoreLabel.hidden=NO;
    }
    
    if (self.settings.sounds) {
        self.soundPlayer=[[SoundDelegate alloc]init];
    }
    
    self.playerTwoName.text=playerTwoName;
    self.playerOneName.text=playerOneName;
    self.test=0;
    
    self.reactor=[Reactor sharedReactor];
    [self.reactor setPlayerOneName:playerOneName playerTwoName:playerTwoName];


    self.view.backgroundColor = [UIColor blackColor];
    
    
    CGAffineTransform trans = CGAffineTransformMakeRotation(3.14);
    [self.playerTwoButton setTransform:trans];
    [self.playerTwoLabel setTransform:trans];
    [self.playerTwoScoreLabel setTransform:trans];
    [self.playerTwoName setTransform:trans];
    
    
    self.playerOneButton.layer.cornerRadius = 10;
    self.playerOneButton.clipsToBounds = YES;
    
    self.playerTwoButton.layer.cornerRadius = 10;
    self.playerTwoButton.clipsToBounds = YES;
    
  //start FirstGame
        [NSTimer scheduledTimerWithTimeInterval: 0 target: self selector:@selector(startNewGame:)userInfo: nil repeats:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(BOOL)prefersStatusBarHidden {
    return YES;
}


//draw some views in gameView
-(void)draw:(Game*)game{
    int labelNumber=0;
    for(int index=0;index<[game.components count];index++){
        
        if ([[game.components objectAtIndex:index] isKindOfClass:[LabelGameComponent class]]) {
            LabelGameComponent *component=[game.components objectAtIndex:index];
            UILabel* label=[[UILabel alloc]initWithFrame:component.frame];
            label.text=component.text;
            SEL selector = NSSelectorFromString(component.colour);
            UIColor* colour = nil;
            if ([UIColor respondsToSelector:selector]) {
                colour=[UIColor performSelector:selector];
            }
            [label setTextColor:colour];
            label.textAlignment=NSTextAlignmentCenter;
            [label  setFont:[UIFont systemFontOfSize:component.fontSize]];
            
            if (labelNumber==0) {
                CGAffineTransform trans = CGAffineTransformMakeRotation(3.14);
                
                [label setTransform:trans];
                labelNumber++;
            }
            [self.gameView addSubview:label];
            
        }
        else{
            ImageGameComponent* component=[game.components objectAtIndex:index];
            UIImageView* image=[[UIImageView alloc]initWithFrame:component.frame];
            UIImage* img=[UIImage imageNamed:component.name];
            image.image=img;
            CGAffineTransform trans = CGAffineTransformMakeRotation(component.trans);
            [image setTransform:trans];
            [self.gameView addSubview:image];
        }
        
    }
}


//Texts for Right Answers - Lazy loading
-(NSMutableArray*) textsForRightAnswer {
    if(!_textsForRightAnswer) {
        _textsForRightAnswer = [NSMutableArray arrayWithObjects:@"Brilliant!",@"Smooth!",@"Not Bad!",@"Top!",@"Oh YES!",@"Well done!", nil];
    }
    return _textsForRightAnswer;
}


//Texts for Wrong Answers
-(NSMutableArray*) textsForWrongAnswer {
    if(!_textsForWrongAnswer) {
        _textsForWrongAnswer = [NSMutableArray arrayWithObjects:@"Drat!",@"Cripes!",@"Argh!",@"You can do better!",@"That was rubbish!",@"Oh NO!",@"You will do better next time!", nil];
    }
    return _textsForWrongAnswer;
}

//Calls when button Click
- (IBAction)buttonClick:(id)sender {
    if (!self.isButtonClick) {
        self.isButtonClick=YES;
    
    [self freezeScreen];
    if ([sender tag] == 1) {
        NSLog(@"dasd");
        if ([self.currentGame isRight] == YES) {
            [self.reactor.playerOne increaseScoreWithType:self.currentGame.type];
            self.playerOneButton.backgroundColor=[UIColor greenColor];
            self.playerOneLabel.text = [self randomForRight];
            self.playerTwoLabel.text = [self randomForWrong];
            if (self.settings.sounds) {
                [self.soundPlayer playSoundWithName:@"beep18" andType:@"mp3"];
            }
            
        }
        else{
            [self.reactor.playerOne decreaseScoreWithType:self.currentGame.type];
            self.playerOneButton.backgroundColor=[UIColor redColor];
            self.playerOneLabel.text = [self randomForWrong];
            if (self.settings.sounds) {
                [self.soundPlayer playSoundWithName:@"beep-03" andType:@"wav"];
            }
            
        }
    }
    
    else{
        if ([self.currentGame isRight] == YES) {
            [self.reactor.playerTwo increaseScoreWithType:self.currentGame.type];
            self.playerTwoButton.backgroundColor=[UIColor greenColor];
            self.playerTwoLabel.text = [self randomForRight];
            self.playerOneLabel.text = [self randomForWrong];
            if (self.settings.sounds) {
                [self.soundPlayer playSoundWithName:@"beep18" andType:@"mp3"];
            }
        }
        else{
            [self.reactor.playerTwo decreaseScoreWithType:self.currentGame.type];
            self.playerTwoButton.backgroundColor=[UIColor redColor];
            self.playerTwoLabel.text = [self randomForWrong];
            if (self.settings.sounds) {
                [self.soundPlayer playSoundWithName:@"beep-03" andType:@"wav"];
            }
        }
        
    }
    
    self.playerOneScoreLabel.text=[NSString stringWithFormat:@"%ld",(long)[self.reactor.playerOne totalScore]];
    self.playerTwoScoreLabel.text=[NSString stringWithFormat:@"%ld",(long)[self.reactor.playerTwo totalScore]];

    [self.currentGame gameOver];
    [NSTimer scheduledTimerWithTimeInterval: 3                                                  target: self selector:@selector(startNewGame:)userInfo: nil repeats:NO];
    }
}



//Random text for Right answer
-(NSString*) randomForRight {
    NSUInteger ind = arc4random_uniform([self.textsForRightAnswer count]);
    return self.textsForRightAnswer[ind];
}



//Random text for Wrong answer
-(NSString*) randomForWrong {
    NSUInteger ind = arc4random_uniform([self.textsForWrongAnswer count]);
    return self.textsForWrongAnswer[ind];
}

//Calls when player click button and  screen is 3 seconds freeze
-(void)freezeScreen{
    self.playerOneButton.userInteractionEnabled=NO;
    self.playerTwoButton.userInteractionEnabled=NO;
}


//Start new game when freeze time run out
-(void)startNewGame:(NSTimer*)timer{
    if (self.settings.sounds) {
        [self.soundPlayer playSoundWithName:@"stufe_3" andType:@"mp3"];
    }
    
    self.isButtonClick=NO;
    self.playerOneButton.userInteractionEnabled=YES;
    self.playerTwoButton.userInteractionEnabled=YES;
    self.gameView.backgroundColor=[UIColor blackColor];
    self.playerOneButton.backgroundColor=[UIColor colorWithRed:0.5 green:0 blue:0 alpha:0.75];
    self.playerTwoButton.backgroundColor=[UIColor colorWithRed:0.5 green:0 blue:0 alpha:0.75];
    for (UIView* u in self.gameView.subviews) {
        [u removeFromSuperview];
    }
    
    if (self.test < [self.settings.gamesToPlay count]) {
    self.currentGame=[[NSClassFromString([NSString stringWithFormat:@"%@",self.settings.gamesToPlay[self.test]]) alloc] init];
    [self.currentGame play];
    [self draw:self.currentGame];
    
    self.playerOneLabel.text = self.currentGame.ruleOfTheGame;
    self.playerTwoLabel.text = self.currentGame.ruleOfTheGame;
    self.currentRound++;
    if (self.currentRound==self.settings.rounds) {
        
            self.test++;
            self.currentRound=0;
    }
    }
    else{
        ResultsViewController *roundsVC = [[ResultsViewController alloc] init];
        [self.navigationController pushViewController:roundsVC animated:YES];
    }
}
    
    
    
    



// Notification for ColorNameGame And MathGame And Capitals Game And PopulationGame And DirectionsGame...."
- (void) SomeGames:(NSNotification *) notification
{
    for (UIView* u in self.gameView.subviews) {
        [u removeFromSuperview];
    }
    [self draw:self.currentGame];
}


//Notification for TimerGame
- (void) TimerGame:(NSNotification *) notification
{
    UILabel* a=self.gameView.subviews[0];
    a.text=notification.userInfo[@"info"];
    CGAffineTransform trans = CGAffineTransformMakeRotation(3.14);
    
    [a setTransform:trans];
    
    
    UILabel* b=self.gameView.subviews[1];
    b.text=notification.userInfo[@"info"];
}


//Notification for WhiteScreenGame
-(void) whiteScreenFunc : (NSNotification*) not{
    [self.gameView setBackgroundColor:[UIColor whiteColor]];
}


//Notification for TTTGame
-(void) TTTGame : (NSNotification*) not {
    for (NSInteger i = 0; i < 9 ; ++ i) {
        ((LabelGameComponent* )(self.gameView.subviews[i])).text = [(TicTacToeGame*)self.currentGame symbolForIndex:i];
    }
    if(((TicTacToeGame*)self.currentGame).isGameOver) {
        [self draw : self.currentGame];
    }
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}
@end
